arithmatic operators: +, -, *, /, **, %, ==, ... variable and symbolic operation: By famous sympy package;def func(var1,var2=x):
...
return result
if cond1:
...
elif cond2:
...
else:
...
while( condition):
...
for (...):
...
a=5;b=9
print(a+b,a-b,a*b,a/b)
print("sum = %s,difference = %s,product = %s, quotient= %s" %(a+b,a-b,a*b,a/b))
def iseven(x):
return x%2==0
iseven(798)
def tax(x):
if x<680000.:
print( "Tax is 0.")
elif x<1200000:
print("Tax is %g" %float(x*0.06-22800))
else:
print("TeX is %s" % float(x*0.12-136000))
tax(1000000)
# add time module to sum a sequence of consecutive integers
import time
sum=0
n=10000000
t0=time.time()
for i in range(n+1):
sum+=i
print(time.time()-t0)
print ("Summation of consecutive natual numbers from 1 to %d is %d." %(n,sum))
It contains among other things:
* a powerful N-dimensional array object
* sophisticated (broadcasting) functions
* tools for integrating C/C++ and Fortran code
* useful linear algebra, random number capabilities, and Fourier transform.
import numPy: prepare numpt to use;
import numpy
numpy.sin(numpy.pi)
get 0import numpy as numpy: give the nicknme
import numpy as np
np.sin(np.pi)
get 0from numpy import *: import all the staff into Python environment, not prefered:
import numpy
sin(pi)
get 0from numpy import sin: import only one numpy function, sin:
import numpy as np
from numpy import sin
sin(np.pi)
get 0import numpy as np
import time
sum=0
n=10000000
t0=time.time()
a=np.linspace(0,n,n+1)
sum=np.sum(a)
print(time.time()-t0)
print ('Summation of consecutive natual numbers from 1 to %d is %d.' %(n,sum))
What is the 10000 term of Fibonicci sequence?
Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined and this allows NumPy to seamlessly and speedily integrate with a wide variety of projects.
Matplotlib is an excellent 2D and 3D graphics library for generating scientific figures. Some of the many advantages of this library include:
One of the of the key features of matplotlib that I would like to emphasize, and that I think makes matplotlib highly suitable for generating figures for scientific publications is that all aspects of the figure can be controlled programmatically. This is important for reproducibility and convenient when one needs to regenerate the figure with updated data or change its appearance.
More information at the Matplotlib web page: http://matplotlib.org/
The easiest way to get started with plotting using matplotlib is often to use the MATLAB-like API provided by matplotlib.
It is designed to be compatible with MATLAB's plotting functions, so it is easy to get started with if you are familiar with MATLAB.
To use this API from matplotlib, we need to include the symbols in the pylab module:
Matplotlib also includes a simple API for generating animations for sequences of figures. With the FuncAnimation function we can generate a movie file from sequences of figures. The function takes the following arguments: fig, a figure canvas, func, a function that we provide which updates the figure, init_func, a function we provide to setup the figure, frame, the number of frames to generate, and blit, which tells the animation function to only update parts of the frame which have changed (for smoother animations):
def init():
# setup figure
def update(frame_counter):
# update figure for new frame
anim = animation.FuncAnimation(fig, update, init_func=init, frames=200, blit=True)
The functionality, animation, works like a chant within IPython notebook with
JSAnimation.
The main idea with object-oriented programming is to have objects that one can apply functions and actions on, and no object or program states should be global (such as the MATLAB-like API). The real advantage of this approach becomes apparent when more than one figure is created, or when a figure contains more than one subplot.
To use the object-oriented API we start out very much like in the previous example, but instead of creating a new global figure instance we store a reference to the newly created figure instance in the fig variable, and from it we create a new axis instance axes using the add_axes method in the Figure class instance fig:
# the following "matplotlib" magic actives the embedded function if any picture created.
%matplotlib inline
import pylab as plt
import numpy as np
from numpy import sin,cos,pi
x=np.linspace(-2,2,1000)
f=x*np.sin(1/x)
plt.plot(x,f)
g=np.sin(x)
plt.plot(x,f,'r-',x,g,'b--',lw=2)
x=np.linspace(0,2*np.pi,100)
plt.polar(x,1+sin(x))+plt.polar(x,2-3*sin(x))
from numpy import sin,cos,pi,ones
x=np.linspace(0,2*np.pi,100)
plt.polar(x,1.8+sin(x)+sin(3*x)/3.,lw=4)+ plt.polar(x,2.2*cos(x)+2*sin(x),lw=6,color="red") \
+ plt.polar(x,-2.2*cos(x)+2*sin(x), lw=6,color="red") + plt.polar(x[55:-5],2*ones(40),lw=8)
plt.figure(figsize=(4,4))
plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)
x=np.linspace(0,2*np.pi,200)
plt.plot(cos(5*x),sin(8*x))
# Arrar of pictures
plt.figure(figsize=(4,4))
plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)
x=np.linspace(0,2*np.pi,200)
[plt.plot(cos(3*x),sin(i*x)) for i in np.arange(5)];
import matplotlib.pylab as plt
from matplotlib import animation
from JSAnimation import IPython_display
from numpy import sin,cos,pi
x1,x2,y1,y2=0,1,0,1
t1=365.256 # one year for Earth
t2=224.701 # one year for Venus
R1=149.6 # 1,000,000 km distance between Earth and Sun
R2=108.21 # 1,000,000 km distance between Venus and Sun
Ratio=R1/R2
def CartesianE(n, R=Ratio):
x=[]
theta= 8*2*pi/t1;
for i in range(n):
x += [R*cos(i*theta),R*sin(i*theta)]
return x
def CartesianV(n, R=1):
x=[]
theta= 8*2*pi/t2;
for i in range(n):
x += [R*cos(i*theta),R*sin(i*theta)]
return x
days=7
n=100
ob= n*days
P=CartesianE(ob)
Q=CartesianV(ob)
k=20
anim=plt.figure(figsize=(8,8));
ax = anim.add_subplot(111)
plt.title("La Vie en Rose",fontsize=14);
plt.ylim([-1.5,1.5]);
plt.xlim([-1.5,1.5]);
def init():
return plt.plot([P[0],Q[0]],[P[1],Q[1]], color='0.2');
PP=[[P[2*k],Q[2*k]] for k in np.arange(100)];
QQ=[[P[2*k+1],Q[2*k+1]] for k in np.arange(100)];
def animate(i):
return [ax.plot(PP[k],QQ[k],color='0.2') for k in np.arange(i)];
animation.FuncAnimation(anim, animate, init_func=init,frames=100)
Eight Earth years is approximated to thirteen Venus ywars:
print(t1*8, t2*13)
Benefit from the javascript library, d3.js, experimental mpld3 avails the visualization functionalities and pythreejs.js:
Not only come the directly Python packages, but Jupyter allows user to bridge the utility in platform to work much flexibly:
# 1. Jupyter path
!jupyter --paths
Enchancement for Jupyter notebook interface:
for instance, we want to install pythreejs, A Python / ThreeJS bridge utilizing the Jupyter widget infrastructure:
shell > pip install pythreejs
shell > jupyter nbextension enable --py pythreejs
Then check the nbextension setting, it should be included in system, such as
shell > jupyter nbextension list
...
jupyter-threejs/extension enabled
- Validating: OK
...
above shows it's join okay.
!jupyter nbconvert introduction.ipynb